
var cfg = require('utils/cfg');
// var socketUtil = require('utils/socketUtil');

//app.js
App({
  onLaunch: function (options) {
    let that = this;
    console.log(options.shareTicket + "--scene :" + options.scene + "---query:" + options.query.uid + "----path:" + options.path);

    if (wx.getStorageSync('userInfo')) {
      this.globalData.userInfo = wx.getStorageSync('userInfo');
    }

    if (wx.getStorageSync('loginUser')) {
      that.globalData.loginUser = wx.getStorageSync('loginUser');
    }

    //生成题目的offset

    if (!wx.getStorageSync('paperOffset')) {
      console.log('生成题目的offset');
      wx.setStorageSync('paperOffset', parseInt(10 * Math.random()));
    }
    
    let updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      if (!res.hasUpdate) {
        console.log('>>>>不需要更新');
        that.wxlogin();
        return;
      }

      console.log('>>>>有新版本更新');
      updateManager.onUpdateReady(function() {
        wx.showModal({
          title: '更新提示',
          showCancel : false,
          content: '新版本已经准备好，是否重启应用？',
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })

      updateManager.onUpdateFailed(function () {
        // 新的版本下载失败
        wx.showModal({
          title: '更新提示',
          showCancel : false,
          content: '小程序更新失败，请手动删除，再打开',
          success: function (res) {
          }
        })
      })
    })


  },

  onShow: function (options) {
    console.log('app onshow');
    this.wxlogin();
  },

  onHide : function() {
    console.log('app onhide');
  },

  initSocket : function() {
    let that = this;
    console.log('>>>>>>>socket well be init()');
    if (that.globalData.socketOpen) {
      return;
    }
    console.log('>>>>>>>socket now init()');
    that.globalData.localSocket = wx.connectSocket({
      url: cfg.socketHost + '/webSocketServer?openId=' + wx.getStorageSync('loginUser').openId,
      data: {
      },
      method: "GET"
    })

    that.globalData.localSocket.onOpen(function (res) {
      console.log('WebSocket连接已打开！');
      that.globalData.socketOpen = true
      for (var i = 0; i < that.globalData.socketMsgQueue.length; i++) {
        that.sendSocketMessage(that.globalData.socketMsgQueue[i])
      }
      that.globalData.socketMsgQueue = [];

      setInterval(function () {
        console.log('>>>>>send heart...');
        that.sendSocketMessage("ping");
      }, 8000);

    })

    that.globalData.localSocket.onMessage(function (res) {
      if (res.data == 'pong') {
        console.log('>>>>>>socket message : ' + res.data);
      } else {
        let resoult = JSON.parse(res.data);
        console.log('>>>>>>socket message: ' + resoult);
        if (1008 === resoult.wsType) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '因队友' + resoult.data+'作答超时，积分清零',
            success: function (res) {
              if (res.confirm) {
                //进入下一轮
                wx.reLaunch({
                  url: '/pages/home/home'
                })
              }
            }
          })

          console.log('>>>>>>>>1008');
        }

        if (1007 === resoult.wsType) {
          wx.showModal({
            title: '提示',
            content: '好友' + resoult.data.nickName + '索要' + resoult.data.integral + '积分',
            cancelText : '拒绝',
            confirmText : '接受',
            success: function (res) {
              if (res.confirm) {
                //接受 请求后台扣除积分和加积分
                wx.request({
                  url: cfg.host + cfg.mwurl.acceptIntegral,
                  data: {
                    giveOpenId: wx.getStorageSync('loginUser').openId,
                    openId: resoult.data.openId,
                    integral: resoult.data.integral,
                    accept: true
                  },
                  success: function (res) {

                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值
                  },
                  method: 'POST'
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })

          return;
        }

        that.globalData.socketCallBack(resoult);
       
      }

    })

    that.globalData.localSocket.onError(function (res) {
      that.globalData.socketOpen = false;
      console.log('WebSocket连接打开失败，请检查！' + res.data);
    })

    that.globalData.localSocket.onClose(function (res) {
      that.globalData.socketOpen = false;
      console.log('WebSocket 已关闭！')
      that.initSocket();
    })


  },

  finishMic : function() {
    let innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = '/images/2.mp3';
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    });

    innerAudioContext.onEnded(() => {
      console.log('播放结束');
    });
  },

  sendSocketMessage : function(msg) {
    let that = this;
    if (that.globalData.socketOpen) {
      that.globalData.localSocket.send({
        data: msg,
        success: function() {
          console.log('>>>>>>websocket发送成功');
        },
        fail : function() {
          console.log('>>>>>>websocket发送失败');
        }
      })
    } else {
      that.globalData.socketMsgQueue.push(msg)
    }
  },

  wxlogin: function () {
    let that = this;
    //调用登录接口
    console.log('登录地址' + cfg.host + cfg.mwurl.wxLogin);

    if (wx.getStorageSync('loginUser')) {
      that.initSocket();
      console.log('已登录');
        return;
    }

    wx.login({
      success: function (res) {
        console.log('code=' + res.code);
        if (res.code) {
          wx.request({
            url: cfg.host + cfg.mwurl.wxLogin,
            data: { code: res.code },
            success: function (resObj) {
              console.log('服务器返回数据:' + resObj.data);
              if (1000 !== resObj.data.code) {
                console.log(resObj.data.message);
                return;
              }
              
              console.log('>>>>>>>>保存登录用户loginUser信息:');
              wx.setStorageSync('loginUser', resObj.data.data);
              that.initSocket();

            }
          })
        } else {
          console.log('获取用户信息失败');
        }
      }
    })
  },
  globalData:{
    userInfo:null,
    loginUser: null,
    localSocket : {},
    socketCallBack: function () {},
    sendSocketMessage : function(){},
    socketOpen : false,
    socketMsgQueue : []
  }
})